<template>
  <el-form ref="skuForm" :model="skuInfo" :rules="rules" label-width="80px" class="my-sku-form">
    <el-form-item label="SPU名称">
      <span>{{ spuName }}</span>
    </el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input v-model="skuInfo.skuName" placeholder="请输入SKU名称" />
    </el-form-item>
    <el-form-item label="价格" prop="price">
      <el-input-number v-model="skuInfo.price" controls-position="right" :min="1020" :max="3050" style="width:100%" @change="handleChange" />
    </el-form-item>
    <el-form-item label="重量" prop="weight">
      <el-input-number v-model="skuInfo.weight" controls-position="right" :min="1" :max="10" style="width:100%" @change="handleChange" />
    </el-form-item>
    <el-form-item label="SKU描述" prop="skuDesc">
      <el-input v-model="skuInfo.skuDesc" type="textarea" placeholder="请输入SKU描述" />
    </el-form-item>
    <el-form-item label="平台属性" prop="skuAttrValueList">
      <el-row>
        <el-col v-for="(attr,index) in attrList" :key="attr.id" :sm="12" :md="8" :lg="6">
          <el-form-item :label="attr.attrName">
            <el-select v-model="skuInfo.skuAttrValueList[index]" placeholder="请选择">
              <el-option v-for="attrValue in attr.attrValueList" :key="attrValue.id" :label="attrValue.valueName" :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <el-row>
        <el-col v-for="(spuSaleAttr,index) in spuSaleAttrList" :key="spuSaleAttr.id" :sm="12" :md="8" :lg="6">
          <el-form-item :label="spuSaleAttr.saleAttrName">
            <el-select v-model="skuInfo.skuSaleAttrValueList[index]" placeholder="请选择">
              <el-option v-for="saleAttrValue in spuSaleAttr.spuSaleAttrValueList" :key="saleAttrValue.id" :label="saleAttrValue.saleAttrValueName" :value="`${spuSaleAttr.id}:${spuSaleAttr.saleAttrName}:${saleAttrValue.id}:${saleAttrValue.saleAttrValueName}`" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table :data="spuImageList" border style="margin-bottom:20px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="75" align="center" />
        <el-table-column label="图片">
          <template v-slot="{row}">
            <el-image style="width: 100px; height: 100px" :src="row.imgUrl" />
          </template>
        </el-table-column>
        <el-table-column label="名称" prop="imgName" />
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button v-if="row.isDefault==='0' " type="primary" @click="setDefaultImg(row)">设置为默认图片</el-button>
            <el-button v-else type="success" disabled>默认图片</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button type="primary" @click="submitSkuForm">确定</el-button>
      <el-button @click="$emit('update:visible',1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { reqGetAttrList } from '@/api/product/attr'
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from '@/api/product/spu'
import { mapState } from 'vuex'
import { reqSaveSkuInfo } from '@/api/product/sku'
export default {
  name: 'SaveSku',
  data() {
    const skuAttrValueListValidator = (rule, value, callback) => {
      if (!value.length) {
        return callback(new Error('请至少选择一个平台属性'))
      }
      callback()
    }
    const skuImageListValidator = (rule, value, callback) => {
      if (!value.length) {
        return callback('请至少选择一张图片')
      }
      callback()
    }
    const skuSaleAttrValueListValidator = (rule, value, callback) => {
      if (!value.length) return callback('请至少选择一个销售属性')
      callback()
    }
    return {
      num: 1,
      attrList: [],
      spuImageList: [],
      spuSaleAttrList: [],
      skuInfo: {
        skuName: '', // SKU名称
        skuDefaultImg: '', // 默认图片
        skuDesc: '', // sku描述
        price: 0, // 价格
        weight: '', // 重量
        skuAttrValueList: [], // 平台属性
        skuImageList: [], // 所选图片的集合
        skuSaleAttrValueList: [] // 销售属性
      },
      rules: {
        skuName: [{ required: true, message: '请输入SKU名称', trigger: 'blur' }],
        skuDesc: [{ required: true, message: '请输入SKU描述', trigger: 'blur' }],
        price: [{ required: true, message: '请输入SKU价格', trigger: 'blur' }],
        weight: [{ required: true, message: '请输入SKU重量', trigger: 'blur' }],
        skuAttrValueList: [{ required: true, validator: skuAttrValueListValidator, trigger: 'change' }],
        skuImageList: [{ required: true, validator: skuImageListValidator, trigger: 'change' }],
        skuSaleAttrValueList: [{ required: true, validator: skuSaleAttrValueListValidator, trigger: 'change' }]
      }
    }
  },
  computed: {
    ...mapState('spu', ['spuId', 'spuName']),
    ...mapState('category', ['category1Id', 'category2Id', 'category3Id'])
  },
  async mounted() {
    // Promise.all()   如果都成功，则结果是成功的，而且响应回来的数据是数组的顺序 有一个失败，则结果是失败
    // Promise.race()  抢先机制 谁先响应回来不确定 上海  天津  武汉  深圳   新疆
    // Promise.allSettled() 类似于All 可以同时发送多个请求，但与all不同的是，允许有失败，不会影响其它请求
    const { category1Id, category2Id, category3Id, spuId } = this
    const [responseAttrList, responseSpuImageList, responseSpuSaleAttrList] = await Promise.allSettled([reqGetAttrList({ category1Id, category2Id, category3Id }), reqGetSpuImageList(spuId), reqGetSpuSaleAttrList(spuId)])
    if (responseAttrList.status === 'fulfilled') {
      this.attrList = responseAttrList.value.data
    }
    if (responseSpuImageList.status === 'fulfilled') {
      this.spuImageList = responseSpuImageList.value.data.map((item) => {
        return {
          ...item, // 对象中原来的属性，依然显示在这里
          isDefault: '0' // 再添加一个属性
        }
      })
    }
    if (responseSpuSaleAttrList.status === 'fulfilled') {
      this.spuSaleAttrList = responseSpuSaleAttrList.value.data
    }
  },
  methods: {
    // 1. 设置默认图片
    setDefaultImg(row) {
      // 先把所有的设置为0
      this.spuImageList.forEach((item) => {
        item.isDefault = '0'
      })
      // 把当前的这个设置为1
      row.isDefault = '1'
      // 保存一下默认图片的地址
      this.skuInfo.skuDefaultImg = row.imgUrl
    },
    // 2. 收集所选的图片
    handleSelectionChange(val) {
      // console.log(val)
      this.skuInfo.skuImageList = val
    },
    // 3. 添加sku
    submitSkuForm() {
      this.$refs.skuForm.validate(async (valid) => {
        if (valid) {
          // 提交之前还要验证一下是否有默认图片
          if (!this.skuInfo.skuDefaultImg) {
            this.$message.error('请设置一个默认图片')
            return
          }
          const { spuId, category3Id } = this
          const { skuName, price, weigth, skuDesc, skuDefaultImg, skuAttrValueList, skuImageList, skuSaleAttrValueList } = this.skuInfo
          const result = await reqSaveSkuInfo({
            spuId,
            category3Id,
            skuName,
            price,
            weigth,
            skuDesc,
            skuDefaultImg,
            skuAttrValueList: skuAttrValueList.filter(Boolean).map((item) => {
              const [attrId, attrName, valueId, valueName] = item.split(':')
              return {
                attrId,
                attrName,
                valueId,
                valueName
              }
            }),
            skuImageList,
            skuSaleAttrValueList: skuSaleAttrValueList.filter(Boolean).map((item) => {
              const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] = item.split(':')
              return {
                saleAttrId,
                saleAttrName,
                saleAttrValueId,
                saleAttrValueName
              }
            })
          })
          if (result.code === 200) {
            this.$message.success('添加SKU对象成功')
            this.$emit('update:visible', 1)
          } else {
            this.$message.error('添加SKU对象失败')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleChange(value) {
      console.log(value)
    }
  }
}
</script>

<style>
</style>
